<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="车辆名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入车辆名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="车牌号码" prop="plateNumber">
        <el-input
          v-model="queryParams.plateNumber"
          placeholder="请输入车牌号码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:vehicle:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:vehicle:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="车辆名称" align="center" prop="name" />
      <el-table-column label="车牌号码" align="center" prop="plateNumber" />
<!--      <el-table-column label="购买日期" align="center" prop="purchaseDate" :formatter="dateFormatter2"  />-->
<!--      <el-table-column label="购买价格" align="center" prop="purchasePrice" />-->
      <el-table-column label="车身颜色" align="center" prop="color" />
<!--      <el-table-column label="座位数" align="center" prop="seatCount" />-->
<!--      <el-table-column label="驾驶员" align="center" prop="driverId" />-->

      <!-- <el-table-column label="行驶证车主" align="center" prop="driverName" /> -->


      <!--      <el-table-column label="油耗" align="center" prop="fuelConsumption" />-->
<!--      <el-table-column label="初始里程数" align="center" prop="initialMileage" />-->
<!--      <el-table-column label="当前里程数" align="center" prop="currentMileage" />-->
      <el-table-column label="车审到期日期" align="center" prop="inspectionExpiryDate" :formatter="dateFormatter2" />
      <el-table-column label="车审到期提醒" align="center" prop="lastInspectionExpiryDate"  :formatter="remainingDaysFormatter" />

      <el-table-column label="保险到期日期" align="center" prop="insuranceExpiryDate" :formatter="dateFormatter2"/>
      <el-table-column label="保险到期提醒" align="center" min-width="120px" prop="lastInsuranceExpiryDate" :formatter="remainingInsuranceDaysFormatter" />

      <el-table-column label="操作" align="center" width="160">

        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail('view', scope.row.id)"
            v-hasPermi="['oa:handover-management:query','oa:vehicle:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:handover-management:update','oa:vehicle:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:handover-management:delete','oa:vehicle:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <VehicleForm ref="formRef" @success="getList" />
  <HandoverManagementDetail ref="detailRef" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { VehicleApi, VehicleVO } from '@/api/oa/vehicle'
import VehicleForm from './VehicleForm.vue'
import { dateFormatter2 } from '@/utils/formatTime'
import dayjs from 'dayjs'
import HandoverManagementDetail from '@/views/oa/vehicle/HandoverManagementDetail.vue'
import UserLabel from '@/views/system/user/UserLabel.vue'

/** 车辆信息 列表 */
defineOptions({ name: 'Vehicle' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<VehicleVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  plateNumber: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const detailRef = ref()

const openDetail = async (type: string, id?: number) => {
  if (!id) {
    message.error('未找到对应的ID')
    return
  }
  try {
    const rowData = await VehicleApi.getVehicle(id)
    console.log(rowData)
    if (detailRef.value && typeof detailRef.value.open === 'function') {
      detailRef.value.open(type, rowData)
    } else {
      console.error('detailRef 没有 open 方法', detailRef.value)
      message.error('detailRef 没有 open 方法')
    }
  } catch (error) {
    message.error('获取车辆信息失败')
  }
}

const daysLeft = (date: Date | string | undefined) => {
  if (!date) return ''
  const now = dayjs()
  const target = dayjs(date)
  const diffDays = target.diff(now, 'day')

  if (diffDays < 0) {
    return h('span', { style: { color: '#ff4949' } }, '已过期')
  }

  if (diffDays <= 7) {
    return h('span', { style: { color: '#e6a23c' } }, `还剩 ${diffDays} 天`)
  }

  return `还剩 ${diffDays} 天`
}

// 使用方式：
const remainingDaysFormatter = (row: VehicleVO) => daysLeft(row.inspectionExpiryDate)
const remainingInsuranceDaysFormatter = (row: VehicleVO) => daysLeft(row.insuranceExpiryDate)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await VehicleApi.getVehiclePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await VehicleApi.deleteVehicle(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await VehicleApi.exportVehicle(queryParams)
    download.excel(data, '车辆信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
